package com.zhuangjie.mvc.sse;

import com.zhuangjie.mvc.sse.properties.SseProperties;
import com.zhuangjie.mvc.sse.service.SSEService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.List;

@Configuration
@EnableScheduling
@EnableConfigurationProperties({SseProperties.class})
@Slf4j
public class SSEApplication implements SchedulingConfigurer {

    @Autowired(required = false)
    private List<SSEService> sseServices;

    @Autowired
    private SseProperties sseProperties;


    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        if ( sseServices != null && !sseServices.isEmpty()) {
            log.info("SSE: 本模块有{}个SSE-service.",sseServices.size());
            for (SSEService sseService : sseServices) {
                Long inspectionInterval = sseProperties.getInspectionInterval();
                if ( Long.valueOf(3000L).compareTo(inspectionInterval) > 0 ) inspectionInterval = 3000L;
                taskRegistrar.addFixedRateTask(sseService::startMaintenance, inspectionInterval);
            }
        }
    }
}
